package Aleehot100;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: c058
 * Package: Aleehot100
 * Description: 39. 组合总和
 *
 * @Author BCXJ
 * @Create 2025/8/8 21:10
 * @Version 1.0
 * @Since 1.0
 */
public class c058 {
    public static void main(String[] args) {
        // int[] arr = {2, 3, 6, 7};
        int[] arr = {2, 3, 6, 7, 1};
        System.out.println(combinationSum(arr, 7));
    }

    static List<List<Integer>> res = new ArrayList<>();

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        res.clear();
        List<Integer> midAns = new ArrayList<>();
        process(midAns, candidates, target, 0, 0);
        return res;
    }

    /**
     *
     * @param midAns     中间1的计算的结果
     * @param candidates 源数组
     * @param target     目标和
     * @param index      当前来到的下标
     * @param curSum     当前的和
     */
    public static void process(List<Integer> midAns, int[] candidates, int target, int index, int curSum) {
        if (index == candidates.length) {
            return;
        }
        if (curSum == target) {
            List<Integer> list = new ArrayList<>(midAns);
            res.add(list);
            return;
        }
        // 分两种情况 ，index的元素要与不要

        // 不要
        process(midAns, candidates, target, index + 1, curSum);
        // 要
        if(curSum + candidates[index] <= target) {
            midAns.add(candidates[index]);
            process(midAns, candidates, target, index, curSum + candidates[index]);
            midAns.remove(midAns.size() - 1);
        }
    }

}
